package show.me.the.money.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;

import javax.xml.parsers.ParserConfigurationException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.WebApplicationContext;
import org.xml.sax.SAXException;

import show.me.the.money.config.schema.SchemaController;
import show.me.the.money.util.context.Context;



import freemarker.ext.dom.NodeModel;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;



public class MappingFileMaker {
	private static Log logger = LogFactory.getLog(MappingFileMaker.class);
	
	public static HashMap<String,Object> makeData(String catalog,String entryName){
		HashMap<String,Object> data = new HashMap<String,Object>();
		String fn = SchemaController.instance().getConfigFilename(entryName);
		File file = new File(fn);
		try {
			NodeModel m = freemarker.ext.dom.NodeModel.parse(file);
			data.put("doc", m);
			data.put("catalog",catalog);
		} catch (SAXException e) {
			logger.error("Parse Schema XML[" + entryName + "] Failed:", e);
		} catch (IOException e) {
			logger.error("Read Schema XML[" + entryName + "] Failed:", e);
		} catch (ParserConfigurationException e) {
			logger.error("ParseConfig Schema XML[" + entryName + "] Failed:", e);
		}
		return data;
	}
	
	public static boolean makeMappingFile(String catalog,String entryName){
		WebApplicationContext wac = AppContextHolder.get();
		Configuration cfg = (Configuration)wac.getBean("freemarkerConfig");
		if(cfg == null){
			logger.error("Get freemarkerConfig instance failed");
			return false;
		}
		Context ctx = (Context)wac.getBean("staticInitContext");
		String mappingHome = ctx.value("server.mappingHome");
	       try {
	        	Template t = cfg.getTemplate("mappingMeaker.ftl");
	            File file = new File(mappingHome + "\\" + entryName + ".hbm.xml"); 
	            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))); 
	            try {
					t.process(makeData(catalog,entryName),out);
				} catch (TemplateException e) {
					logger.error("Process MappingFile template failed:", e);
					return false;
				} 
				return true;
	        } 
	        catch (IOException e) {
	        	logger.error("Process MappingFile template IO failed:", e);
	        	return false;
	        }				
	}
	
	
	public  static  void main(String[] args){
	
	}
}
